//
//  BDMallViewController.m
//  BadBoy
//
//  Created by wen on 2017/4/14.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDMallViewController.h"
#import "BDMallProductModel.h"
#import "GoodsDetailsViewController.h"
#import "BDUserModel.h"
#import "SDCycleScrollView.h"
#import "BDMallCollectionViewCell.h"
#import "UIButton+WebCache.h"
#import "BDGoumaiJiluViewController.h"

@interface BDMallViewController ()<UICollectionViewDelegate,UICollectionViewDataSource, UIScrollViewDelegate, SDCycleScrollViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) SDCycleScrollView *lunboView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@end

@implementation BDMallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    self.title = ASLocalizedString(@"商城");

    [self.indicatorView startAnimating];
    [self request];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)request{
    NSString *url = [NSString stringWithFormat:@"%@banners?position=2", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        NSMutableArray *lunboArray = [NSMutableArray array];
        NSArray *arr = x;
        for (int i = 0; i < arr.count; i++) {
            [lunboArray addObject:[arr[i] objectForKey:@"cover"]];
        }
        self.lunboView.imageURLStringsGroup = lunboArray;
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求广告轮播图失败"));
    }];
    
    NSString *url2 = [NSString stringWithFormat:@"%@products?page=%@&size=%@&category=1&type=2", KBDBaseURL, self.startPage, self.pageSize];
    
    RACSignal *signal2 = [[BDNetworkingServer yy_GET:url2 parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal2 subscribeNext:^(id  _Nullable x) {
        NSMutableArray *arr = [BDMallProductModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        [self.datasource addObjectsFromArray:arr];
        
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
    }];
    
    [signal2 subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求数据失败%@"), error);
    }];
    
    [[RACSignal merge:@[signal, signal2]] subscribeCompleted:^{
        [self.indicatorView stopAnimating];
        [self.collectionView reloadData];
    }];
    
}

- (void)requestBanner{
    
}

- (void)requestDatasource{
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.topView.bottom = kBDTopHeight - scrollView.contentOffset.y;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datasource.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    BDMallCollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
        
    BDMallProductModel *model = self.datasource[indexPath.row];
    [cell configeWithModel:model needLeftLine:indexPath.row % 2];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    GoodsDetailsViewController *detailsVC = [[GoodsDetailsViewController alloc] init];
    BDMallProductModel *model = self.datasource[indexPath.item];
    detailsVC.detailsModel = model;
    detailsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailsVC animated:YES];
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(kBDScreenWidth / 2.0, kBDScreenWidth / 2.0);
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) collectionViewLayout:flowLayout];
        _collectionView.contentInset = UIEdgeInsetsMake(self.topView.height, 0, 0, 0);
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        [_collectionView registerClass:[BDMallCollectionViewCell class] forCellWithReuseIdentifier:@"CELL"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"footer"];
        [self.view insertSubview:_collectionView atIndex:0];
    }
    return _collectionView;
}

- (UIView *)topView{
    if (!_topView) {
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, 0)];
        _topView.backgroundColor = [UIColor clearColor];
        [_topView addSubview:self.lunboView];
        
        UIButton *jifenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        jifenButton.frame = CGRectMake(0, self.lunboView.bottom, kBDScreenWidth / 2.0, 50);
        [jifenButton setTitleColor:[UIColor colorWithHexString:@"#101010"] forState:UIControlStateNormal];
        
        NSString *titleString = [NSString stringWithFormat:ASLocalizedString(@"余额 %.2f 元"),[BDUserModel getCurrentUser].balance];
        
        NSMutableAttributedString *titleAttributedString = [[NSMutableAttributedString alloc] initWithString:titleString];
        NSRange range1 = [titleString rangeOfString:[NSString stringWithFormat:@"%.2f",[BDUserModel getCurrentUser].balance]];
        [titleAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#ff4f00"] range:range1];

        
        [jifenButton setAttributedTitle:titleAttributedString forState:UIControlStateNormal];
//        [jifenButton setTitleColor:[UIColor colorWithHexString:@"#101010"] forState:UIControlStateNormal];
        jifenButton.titleLabel.font = [UIFont systemFontOfSize:17];
        [jifenButton setImage:[UIImage imageNamed:@"jifeng_icon"] forState:UIControlStateNormal];
        jifenButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
        [_topView addSubview:jifenButton];
        
        UIButton *duihuanJiluButton = [UIButton buttonWithType:UIButtonTypeCustom];
        duihuanJiluButton.frame = CGRectMake(kBDScreenWidth / 2.0, self.lunboView.bottom, kBDScreenWidth / 2.0, 50);
        [duihuanJiluButton setTitle:ASLocalizedString(@"购买记录")forState:UIControlStateNormal];
        [duihuanJiluButton setTitleColor:[UIColor colorWithHexString:@"#101010"] forState:UIControlStateNormal];
        duihuanJiluButton.titleLabel.font = [UIFont systemFontOfSize:17];
        [duihuanJiluButton setImage:[UIImage imageNamed:@"jilu_icon"] forState:UIControlStateNormal];
        duihuanJiluButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
        [_topView addSubview:duihuanJiluButton];
        
        [[duihuanJiluButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [BDUserModel judgeCurrentUserWithNormalBlock:^{
                BDGoumaiJiluViewController *goumaiJiluVC = [[BDGoumaiJiluViewController alloc] init];
                goumaiJiluVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:goumaiJiluVC animated:YES];
            }];
        }];
        
        UIView *fengeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 25)];
        fengeView.backgroundColor = kBDColorGray;
        fengeView.centerY = duihuanJiluButton.centerY;
        fengeView.centerX =kBDScreenWidth / 2.0;
        [_topView addSubview:fengeView];
        
        UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 10)];
        grayView.backgroundColor = kBDColorGray;
        grayView.top = duihuanJiluButton.bottom;
        [_topView addSubview:grayView];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textColor = [UIColor colorWithHexString:@"767676"];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.text = ASLocalizedString(@"大家都在看");
        [titleLabel sizeToFit];
        titleLabel.height = 35;
        titleLabel.top = grayView.bottom;
        titleLabel.left = 10;
        [_topView addSubview:titleLabel];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        lineView.backgroundColor = kBDColorGray;
        lineView.top = titleLabel.bottom;
        [_topView addSubview:lineView];
        
        _topView.height = lineView.bottom;
        [self.view addSubview:_topView];
    }
    return _topView;
}

- (SDCycleScrollView *)lunboView{
    if (!_lunboView) {
        self.lunboView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kBDScreenWidth, 165 * kBDScreenWidth / 375) delegate:self placeholderImage:[UIImage imageNamed:@"shop_pic"]];
    }
    return _lunboView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        _indicatorView.frame = CGRectMake(0, kBDTopHeight, kBDScreenWidth, 50);
        [self.view addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
